package com.example.demo01.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.example.demo01.R;

public class BindService extends Service {

    //用于播放音乐等媒体资源
    private MediaPlayer mediaPlayer;

    private MyBinder myBinder = new MyBinder();

    public BindService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (mediaPlayer == null) {
            //. 创建媒体资源实例
            mediaPlayer = MediaPlayer.create(this, R.raw.music);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {

        //. 绑定服务时，返回Binder对象
        return myBinder;
    }

    //. 播放
    public void play() {
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();
        }
        Log.i("TAG", "播放中");
    }

    //. 暂停
    public void pause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
        Log.i("TAG", "已暂停");
    }


    public class MyBinder extends Binder {

        public BindService getService() {
            //自己返回自己的实例，实例给到activity
            return BindService.this;
        }
    }

    //. 解绑服务时，释放MediaPlayer
    @Override
    public boolean onUnbind(Intent intent) {
        releaseMediaPlayer();
        Log.i("TAG", "服务销毁");
        return super.onUnbind(intent);
    }

    //. 销毁服务时，释放MediaPlayer
    @Override
    public void onDestroy() {
        super.onDestroy();
        releaseMediaPlayer();
        Log.i("TAG", "服务销毁");
    }

    private void releaseMediaPlayer() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.stop();
                mediaPlayer.release();
            } catch (Exception e) {
                Log.e("TAG", "释放MediaPlayer失败", e);
            } finally {
                mediaPlayer = null;
            }
        }
    }
}
